package com.xxx.auth.service;

import com.xxx.auth.common.util.PasswordEncoder;
import com.xxx.auth.common.web.exception.DataConflictValidationException;
import com.xxx.auth.entity.User;
import com.xxx.auth.entity.enums.Status;
import com.xxx.auth.repository.UserRepository;
import com.xxx.auth.web.vo.RegisterForm;
import jakarta.persistence.criteria.Predicate;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
@RequiredArgsConstructor
public class UserService {

    private final UserRepository userRepository;

    /**
     * 注册
     *
     * @param form 表单数据
     * @return 用户id
     */
    public String register(RegisterForm form) {
        // 查询用户是否存在
        if (userRepository.findOne(((root, query, criteriaBuilder) -> {
            Predicate usernamePredicate = criteriaBuilder.equal(root.get("username"), form.getUsername());
            Predicate statusPredicate = criteriaBuilder.equal(root.get("status"), Status.NORMAL);
            return criteriaBuilder.and(usernamePredicate, statusPredicate);
        })).isPresent()) {
            throw new DataConflictValidationException("用户名已存在");
        }

        User user = new User();
        BeanUtils.copyProperties(form, user);
        user.setPassword(new PasswordEncoder().encode(form.getPassword()));
        userRepository.save(user);

        return user.getId();
    }

}
